<?php

namespace App\Controller\Api\Wuliu;

use App\Base\BaseController4Restful;
use App\Entity\Wuliu\WuliuUser;
use App\Repository\Wuliu\WuliuUserRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class ApiWuliuUserController extends BaseController4Restful
{
    /**
     * @Route("/api/wuliuUsers", name="apiGetWuliuUsers",methods={"GET","POST"})
     */
    public function apiGetWuliuUsers(WuliuUserRepository $repository,Request $request)
    {
        switch ($request->getMethod()) {
            case "POST":
                $data = $this->getRequestData();
                /**@var $WuliuUser WuliuUser*/
                $WuliuUser = $this->createEntity($data,WuliuUser::class);
                $this->myEm()->persist($WuliuUser);$this->myEm()->flush();
                return $this->json_out(200,"创建成功", $WuliuUser);
            default:
                if (!$page = $this->getParamRequired("page")) {$page = 1;}
                $limit = 10;
                $offset = (int)abs($limit * ($page - 1));
                $total = $repository->count([]);
                $this->setMeta($page,$total,$limit);
                $list = $repository->findBy(array(),array(),$limit,$offset);
                return $this->json_out(200,"获取成功", $list);
        }
    }

    /**
     * @Route("/api/wuliuUsers/{id}", name="apiAddWuliuUsers",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiUpdateWuliuUsers(WuliuUser $WuliuUser,Request $request)
    {
        $data = $this->getRequestData();
        switch ($request->getMethod()) {
            case "DELETE":
                $this->myEm()->remove($WuliuUser);$this->myEm()->flush();
                return $this->json_out(200,"已移除");
            case "PATCH":
            case "PUT":
                /**@var $WuliuUser WuliuUser*/
                $WuliuUser = $this->updateEntity($data,WuliuUser::class,$WuliuUser);
                break;
            case "Get":
            default:
        }
        $this->myEm()->persist($WuliuUser);$this->myEm()->flush();
        return $this->json_out(200,"获取成功", $WuliuUser);
    }

    /**
     * @Route("/api/get_user_info", name="apiWuliuUsersGetInfo")
     */
    public function apiWuliuUsersGetInfo(
        WuliuUserRepository $wuliuUserRepository
    )
    {
        $user = $this->getUser();
        $data = [];
//        dump($user);
        if (!$user) {
            $data["login"] = 0;
            $data["user"] = null;
            $data["wuser"] = null;
            $data["vip"] = 0;
        }else{
            $wuer = $wuliuUserRepository->findOneBy(array('user'=>$user));
            $data["login"] = 1;
            $data["user"] = $user;
            $data["wuser"] =$wuer;
            $data["vip"] =$wuer?$wuer->getExpireAt()->getTimestamp() > time()?1:0:0;
        }
        $this->setGroups("user","level");
        return $this->json_out(1,"OK",$data);
    }
}
